#include "map_baidu.h"
#include "ui_map_baidu.h"
#include <QUrl>            // 处理URL
#include <limits>          // 添加limits头文件

// 添加比较函数结构体
struct CompareNode {
    bool operator()(const QPair<double, int>& a, const QPair<double, int>& b) const {
        return a.first > b.first;
    }
};

map_baidu::map_baidu(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::map_baidu)
{
    ui->setupUi(this);

    initGraph();
    QPixmap pixmap(":/img/33.png");

    ui->label_4->setPixmap(pixmap);
    ui->label_4->setScaledContents(true);  // 关键代码：图片充满整个label

    for (int i=0; i<g.size(); i++) {
        ui->comboStart_2->addItem(g.name(i), i);
        ui->comboEnd_2->addItem(g.name(i), i);
    }
    connect(ui->btnCalc_2, &QPushButton::clicked, this, &map_baidu::on_btnCalc_clicked);
}

void map_baidu::initGraph() {
    g.resize(15);
    // 设置名称（示例）
    g.setName(0, QString::fromLocal8Bit("老图书馆"));
    g.setName(1, QString::fromLocal8Bit("汇文楼"));
    g.setName(2, QString::fromLocal8Bit("新图书馆"));
    g.setName(3, QString::fromLocal8Bit("A8"));
    g.setName(4, QString::fromLocal8Bit("A食堂"));
    g.setName(5, QString::fromLocal8Bit("B食堂"));
    g.setName(6, QString::fromLocal8Bit("主楼"));
    g.setName(7, QString::fromLocal8Bit("体育馆"));
    g.setName(8, QString::fromLocal8Bit("联通广场"));
    g.setName(9, QString::fromLocal8Bit("A区游泳馆"));
    g.setName(10, QString::fromLocal8Bit("音乐厅"));
    g.setName(11, QString::fromLocal8Bit("医院"));
    g.setName(12, QString::fromLocal8Bit("2号教学楼"));
    g.setName(13, QString::fromLocal8Bit("音乐厅"));
    g.setName(14, QString::fromLocal8Bit("正校门"));

    // 添加边（假设的时间，单位秒）
    g.addUndirectedEdge(0,1,120);
    g.addUndirectedEdge(1,2,90);
    g.addUndirectedEdge(2,3,60);
    g.addUndirectedEdge(3,4,100);
    g.addUndirectedEdge(0,7,80);
    g.addUndirectedEdge(7,5,60);
    g.addUndirectedEdge(5,6,50);
    g.addUndirectedEdge(6,14,200);
    g.addUndirectedEdge(8,4,70);
    g.addUndirectedEdge(9,0,150);
    g.addUndirectedEdge(10,14,100);
    g.addUndirectedEdge(11,3,110);
    g.addUndirectedEdge(12,13,90);
    g.addUndirectedEdge(13,9,120);
    // ... 你可以继续补充
}

void map_baidu::on_btnCalc_clicked() {
    int s = ui->comboStart_2->currentData().toInt();
    int t = ui->comboEnd_2->currentData().toInt();

    auto result = g.shortestTimePath(s, t);
    double timeSec = result.first;
    auto path = result.second;

    ui->textResult_2->clear();
    if (timeSec == std::numeric_limits<double>::infinity()) {
        ui->textResult_2->setText(QString("There is no path to reach"));
        return;
    }

    QString text;
    text += QString::fromLocal8Bit("预计最短用时: %1 秒\n路线: ").arg(timeSec);

    for (int i=0; i<path.size(); i++) {
        text += g.name(path[i]);
        if (i < path.size()-1) text += " -> ";
    }
    ui->textResult_2->setText(text);
}

map_baidu::~map_baidu()
{
    delete ui;
}

void map_baidu::on_pushButton_clicked()
{
    emit show_Menu();
}
